package com.huluobo.a2110mvvmjetpackdemo2.lifecycle;

import android.os.CountDownTimer;
import android.util.Log;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

import com.huluobo.a2110mvvmjetpackdemo2.viewmodel.ADViewModel;

/**
 * Created by LC on 2023/12/29.
 * 广告的管理器
 */
public class ADManager implements LifecycleObserver {

    public ADManager(ADViewModel adViewModel) {
        countDownTimer = new CountDownTimer(adViewModel.millisInFuture, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                Log.i("TagA", "广告剩余:" + (int) millisUntilFinished / 1000);
//                if (adManagerListener != null) {
//                    //4.对应位置调用接口中的方法
//                    adManagerListener.timing((int) millisUntilFinished / 1000);
//                }
                adViewModel.setTimingResult(millisUntilFinished / 1000);
            }

            @Override
            public void onFinish() {
                Log.i("TagA", "广告结束");
//                if (adManagerListener != null) {
//                    adManagerListener.finish();
//                }
            }
        };
    }

    private CountDownTimer countDownTimer;

    //实现了LifeCycleObserver 现在可以通过观察被观察者的生命周期啦调用对应的方法
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void start() {
        Log.i("TagA", "开始计时");
        countDownTimer.start();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void stop() {
        Log.i("TagA", "结束计时");
        countDownTimer.cancel();
    }

//    //1.创建接口
//    interface ADManagerListener {
//        void timing(int second);
//
//        void finish();
//    }
//
//    //2.声明接口
//    private ADManagerListener adManagerListener;
//
//    ///3.set方法
//    public void setAdManagerListener(ADManagerListener adManagerListener) {
//        this.adManagerListener = adManagerListener;
//    }
}
